package com.fishingwithme.android.ui.screens.map

import android.content.Context
import android.util.Log
import com.fishingwithme.android.ui.screens.map.handlers.CleanUpHandler
import com.fishingwithme.android.ui.screens.map.handlers.DrawLineEventHandler
import com.fishingwithme.android.ui.screens.map.handlers.DrawNavigationLineHandler
import com.fishingwithme.android.ui.screens.map.handlers.DrawPolygonEventHandler
import com.fishingwithme.android.ui.screens.map.handlers.DrawSpotNavigationLineEventHandler
import com.fishingwithme.android.ui.screens.map.handlers.FinishHandler
import com.fishingwithme.android.ui.screens.map.handlers.JumpToCurrentLocationEventHandler
import com.fishingwithme.android.ui.screens.map.handlers.MapEventHandler
import com.fishingwithme.android.ui.screens.map.handlers.MapRefreshHandler
import com.fishingwithme.android.ui.screens.map.handlers.PickupPointEventHandler
import com.fishingwithme.android.ui.screens.map.handlers.SwitchMapTypeEventHandler
import com.tencent.tencentmap.mapsdk.maps.TencentMap

/**
 * MapWrapperController接口的默认实现
 */
class DefaultMapWrapperController(
    override val context: Context,
    // Replace the old data map with the new MapOperationContext
    override val mapContext: MapOperationContext = MapOperationContext()
) :
    MapWrapperController {
    var refreshHandler: EventHandler? = null

    // 创建地图处理器列表
    val mapHandlers = mapOf(
        Pair("pickupPoint", PickupPointEventHandler()),
        Pair("jumpToCurrentLocation", JumpToCurrentLocationEventHandler()),
        Pair("drawPolygon", DrawPolygonEventHandler()),
        Pair("drawLine", DrawLineEventHandler()),
        Pair("switchMapType", SwitchMapTypeEventHandler()),
        Pair("drawNavigationLine", DrawNavigationLineHandler()),
        Pair("drawSpotNavLine", DrawSpotNavigationLineEventHandler()),
        Pair("finish", FinishHandler()),
        Pair("cleanup", CleanUpHandler()),
        Pair("refreshSpots", MapRefreshHandler())
    )

    // 存储模块和对应的处理器keys配置
    override val targets: Map<String, List<String>> = mapOf(
        "spot" to listOf("drawNavigationLine"),
        "circle" to listOf("drawLine"),
        "addSpot" to listOf(
            "finish",
            "drawSpotNavLine",
            "switchMapType",
            "cleanup",
            "jumpToCurrentLocation"
        ),
        "addCircle" to listOf(
            "finish",
            "drawPolygon",
            "switchMapType",
            "cleanup",
            "jumpToCurrentLocation"
        ),
        "spotHome" to listOf("jumpToCurrentLocation", "switchMapType", "refreshSpots"),
        "updateSpot" to listOf(
            "finish",
            "drawSpotNavLine",
            "switchMapType",
            "cleanup",
            "drawNavigationLine"
        )
    )

    // 存储地图和上下文，用于延迟初始化
    private var tencentMap: TencentMap? = null

    // Flag to track if the map has been destroyed
    private var isMapDestroyed = false

    // 当前选中的处理器
    private var currentHandler: MapEventHandler? = null

    // 存储所有已初始化的处理器
    private val initializedHandlers = mutableMapOf<String, MapEventHandler>()

    // 当前模块key
    private var currentModuleKey: String = ""

    // 导航回调函数
    override var onNavigateBack: ((String) -> Unit)? = null

    /**
     * 初始化地图控制器
     */
    override fun init(moduleKey: String, tencentMap: TencentMap): List<SideBarItem> {
        this.currentModuleKey = moduleKey
        this.tencentMap = tencentMap

        return targets[moduleKey]?.filter { handlerKey ->
            ensureHandlerInitialized(handlerKey)
            val handler = mapHandlers[handlerKey]
            if (handler != null && !handler.showMenu) {
                refreshHandler = handler
            }
            handler != null && handler.showMenu
        }?.mapNotNull { handlerKey ->
            mapHandlers[handlerKey]?.let { mapHandler ->
                if (mapHandler.initializeData) {
                    mapHandler.active()
                }
                SideBarItem(
                    key = mapHandler.key,
                    icon = mapHandler.icon,
                    handler = mapHandler
                )
            }
        } ?: emptyList()
    }

    override fun doMapRefresh() {
        // Only refresh if map is not destroyed
        if (!isMapDestroyed && tencentMap != null) {
            try {
                refreshHandler?.active()
            } catch (e: Exception) {
                Log.w("Controller", "Error during map refresh", e)
            }
        }
    }

    /**
     * 确保处理器已初始化
     */
    fun ensureHandlerInitialized(handlerKey: String) {
        try {
            if (!initializedHandlers.containsKey(handlerKey) && tencentMap != null) {
                mapHandlers[handlerKey]?.let { handler ->
                    handler.initHandler(tencentMap!!, context, this)
                    initializedHandlers[handlerKey] = handler
                }
            }
        } catch (e: Exception) {
            Log.d("Controller", "${e.message}")
        }
    }

    /**
     * 设置当前活动的处理器
     */
    fun setActiveHandler(handler: MapEventHandler) {
        currentHandler?.let { current ->
            if (current != handler) {
                current.deActive()
                this.currentHandler = handler
            }
        } ?: run {
            // If there's no current handler, set this as the current handler and register controller
            this.currentHandler = handler
        }
    }

    /**
     * Clean up all map elements when needed
     */
    fun cleanup() {
        mapContext.clearAllElements()
    }

    /**
     * Clean up all data and elements
     */
    fun fullCleanup() {
        mapContext.clearAllElements()
        mapContext.data.clear()
    }

    /**
     * Mark the map as destroyed to prevent further operations
     */
    fun onDestroy() {
        isMapDestroyed = true
        tencentMap = null
    }

}